import json
from django.http import JsonResponse
from django.views import View

from lapi_app.models.bug_model.bug import Bug_menu
from lapi_app.models.testcase_model.testcase import Testcase
from lapi_app.models.testcase_model.testcase_tree import Menu
from lapi_app.view.bug_view.bug_serializers import Bug_OrganizeTableModelSerializer
from lapi_app.view.testcase_view.serializers import OrganizeTableModelSerializer


# 获取接口目录树
def api_menu_tree(request):
    menu_list = Menu.objects.filter(type__in=(0, 1, 2)).order_by("type", "id")
    Serializer = OrganizeTableModelSerializer(menu_list, many=True)
    result = OrganizeTableModelSerializer.xTree(Serializer.data)
    return JsonResponse({"code": 200, "content": result})


# 获取ui自动化目录树
def ui_menu_tree(request):
    menu_list = Menu.objects.filter(type__in=(0, 3, 4)).order_by("type", "id")
    Serializer = OrganizeTableModelSerializer(menu_list, many=True)
    result = OrganizeTableModelSerializer.xTree(Serializer.data)
    return JsonResponse({"code": 200, "content": result})


# 获取bug目录树
def bug_menu_tree(request):
    data = json.loads(request.body)
    menu_list = Bug_menu.objects.filter(type__in=(0, 1, 2), project_id=data["project_id"]).order_by("type", "id")
    Serializer = Bug_OrganizeTableModelSerializer(menu_list, many=True)
    result = OrganizeTableModelSerializer.xTree(Serializer.data)
    return JsonResponse({"code": 200, "content": result})


# 删除目录节点
def delete_menu(request):
    body = json.loads(request.body)
    ids = body["id"]
    if ids == '':
        return JsonResponse({
            "code": 100,
            "message": "必要参数不能为空"
        })
    elif Menu.objects.filter(pid=ids).exists():
        return JsonResponse({
            "code": 101,
            "message": "目录下存在文件或接口，不可删除"
        })
    elif not Menu.objects.filter(id=ids):
        return JsonResponse({
            "code": 102,
            "message": "目标id不存在，无法删除"
        })
    else:
        Testcase.objects.filter(id=Menu.objects.get(id=ids).testcase_id).delete()
        Menu.objects.filter(id=ids).delete()
        return JsonResponse({
            "code": 200,
            "message": "删除成功"
        })
